﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Xml.XPath;

namespace Songhay.Data.GenericWeb.Procedures
{
    using Songhay.Data.Common;
    using Songhay.Data.GenericWeb.DataTransferContracts;
    using Songhay.Data.GenericWeb.Properties;

    /// <summary>
    /// Insert procedures into the DBMS.
    /// </summary>
    public static partial class Insert
    {
        /// <summary>
        /// Inserts the specified Fragment data into the DBMS.
        /// </summary>
        /// <param name="commonConnection">The Common connection.</param>
        /// <param name="fragment">The Fragment data according to the data transfer contract.</param>
        /// <returns>Returns the unique identifier of the inserted item.</returns>
        public static int? Fragment(DbConnection commonConnection, IFragment fragment)
        {
            if(commonConnection == null) throw new ArgumentNullException("commonConnection", "The Common Connection is null.");
            if(fragment == null) throw new ArgumentNullException("fragment", "The Input Fragment is null.");

            Dictionary<string, object> paramSet = new Dictionary<string, object>();
            paramSet.Add("@fragmentName", fragment.FragmentName);
            paramSet.Add("@FragmentDisplayName", fragment.FragmentDisplayName);
            paramSet.Add("@SortOrdinal", fragment.SortOrdinal);
            paramSet.Add("@ItemChar", fragment.ItemChar);
            paramSet.Add("@ItemText", fragment.ItemText);
            paramSet.Add("@CreateDate", fragment.CreateDate);
            paramSet.Add("@EndDate", fragment.EndDate);
            paramSet.Add("@ModificationDate", fragment.ModificationDate);
            paramSet.Add("@DocumentId", fragment.DocumentId);
            paramSet.Add("@PrevFragmentId", fragment.PrevFragmentId);
            paramSet.Add("@NextFragmentId", fragment.NextFragmentId);
            paramSet.Add("@IsPrevious", fragment.IsPrevious);
            paramSet.Add("@IsNext", fragment.IsNext);
            paramSet.Add("@IsWrapper", fragment.IsWrapper);
            paramSet.Add("@ClientId", fragment.ClientId);
            paramSet.Add("@IsActive", fragment.IsActive);

            using(DbCommand cmd = commonConnection.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = Resources.InsertFragment;

                DbParameter[] paramArray = CommonParameter.GetParameters(cmd, paramSet);
                cmd.Parameters.AddRange(paramArray);

                object newId = cmd.ExecuteScalar();

                return FrameworkType.ParseInt32(newId);
            }
        }
    }
}
